package cn.lanqiao.springbootproject.config;

import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 解决跨域
 */
@Configuration
public class CorsFilterConfig {

    /**
     * 开启跨域访问过滤器
     *
     * @date 2021/4/29 9:50
     */
    @Bean
    public CorsFilter corsFilter() {
        //创建CorsConfiguration对象后添加配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //设置放行哪些原始域，若是设置setAllowCredentials，则不能使用*
//        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOrigin("http://localhost:5173");
        //放行哪些原始请求头部信息
        corsConfiguration.addAllowedHeader("*");
        //放行哪些请求方式
        corsConfiguration.addAllowedMethod("*");
        //前端开启cookie操作，后端需要配合开启允许通行
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //2. 添加映射路径
        source.registerCorsConfiguration("/**", corsConfiguration);

        MyCorsFilter corsFilter = new MyCorsFilter(source);
        corsFilter.getOrder();
        return corsFilter;
    }

    class MyCorsFilter extends CorsFilter implements OrderedFilter {

        public MyCorsFilter(CorsConfigurationSource configSource) {
            super(configSource);
        }

        @Override
        public int getOrder() {
            return -1;
        }
    }
}
